import { FC, useEffect, useMemo, useState } from "react";
import {
  Button,
  Form,
  Input,
  Message,
  Modal,
  Select,
  Space,
} from "@arco-design/web-react";
import { css } from "@emotion/css";
import { useAPI } from "../../hooks/useAPI.ts";
import { RadarInfo } from "../../api/types/radar-info.tsx";
import { useMutation, useQuery } from "react-query";
import { SearchBuildingParams } from "../../api/types/building.tsx";

export const bed = {
  "0": "左床",
  "1": "中床",
  "2": "右床",
  "3": "厕所",
};

export const bedList = [
  {
    label: "左床",
    value: 0,
  },
  {
    label: "中床",
    value: 1,
  },
  {
    label: "右床",
    value: 2,
  },
  {
    label: "厕所",
    value: 3,
  },
];

export interface AddRadarModalProps {
  visible?: boolean;
  onClose?: () => void;
  title?: string;
  isEdit?: boolean;
  radarId?: number;
  onSuccess?: () => void;
}

export const RadarInfoModal: FC<AddRadarModalProps> = ({
  visible,
  onClose,
  title,
  isEdit = false,
  radarId,
  onSuccess,
}) => {
  const api = useAPI();
  const [formRef] = Form.useForm();
  const [radarData, setRadarData] = useState<RadarInfo>();
  const selectedBuildingId = Form.useWatch("buildingId", formRef);
  const selectedFloorId = Form.useWatch("floorId", formRef);
  const selectedRoomId = Form.useWatch("roomId", formRef);

  useEffect(() => {
    const fetchData = async () => {
      if (visible && isEdit) {
        try {
          const response = await api.getRadarById(radarId!);
          formRef.setFieldsValue(response.data.data);
          setRadarData(response.data.data);
        } catch (error) {
          if (error instanceof Error) {
            Message.error(error.message);
          }
        }
      }
    };
    fetchData();
  }, [visible, api, formRef, radarId]);

  const buildingListParams: SearchBuildingParams = {
    pageNum: 1,
    pageSize: 1000,
  };
  const { data: buildingList } = useQuery(
    ["query-building-list", buildingListParams],
    async () => {
      const response = await api.getBuildingList(buildingListParams);
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    },
  );
  const { data: buildingInfo } = useQuery(
    ["query-building-info", selectedBuildingId],
    async () => {
      const response = await api.getBuildingInfoById(selectedBuildingId);
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    },
    {
      enabled: selectedBuildingId !== undefined,
    },
  );
  const rooms = useMemo(() => {
    const floor = buildingInfo?.floors?.find(
      (floor) => floor.id === selectedFloorId,
    );
    if (!floor) return [];
    return floor.rooms;
  }, [buildingInfo?.floors, selectedFloorId]);

  const submitForm = useMutation(async () => {
    try {
      const values = await formRef.validate();
      values.status = 0;
      if (isEdit) {
        values.id = radarId;
        values.bed = radarData?.bed;
        values.location = radarData?.bed;
        await api.updateRadar(values);
      } else {
        await api.addRadar(values);
      }
      if (onSuccess) onSuccess();
      formRef.resetFields();
    } catch (error) {
      if (error instanceof Error) {
        Message.error(error.message);
      } else {
        Message.error("操作失败，请稍后重试");
      }
    }
  });

  return (
    <Modal
      style={{ width: "600px" }}
      visible={visible}
      onCancel={() => {
        formRef.resetFields();
        onClose?.();
      }}
      title={title}
      footer={null}
      unmountOnExit
      mountOnEnter
    >
      <Form form={formRef} initialValues={radarData!}>
        <Form.Item
          label="雷达名称"
          field="name"
          rules={[
            {
              required: true,
              message: "雷达名称不得为空",
            },
          ]}
        >
          <Input placeholder="请输入雷达名称" />
        </Form.Item>
        <Form.Item
          label="雷达IP"
          field="ip"
          rules={[
            {
              required: true,
              validator(value, cb) {
                const ipReg =
                  /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/;
                if (ipReg.test(value)) {
                  return cb(null);
                }
                cb("请输入正确的IP地址");
              },
            },
          ]}
        >
          <Input placeholder="请输入雷达IP" />
        </Form.Item>

        <Form.Item
          label="雷达MAC"
          field="mac"
          rules={[
            {
              required: true,
              message: "MAC不得为空",
            },
          ]}
        >
          <Input placeholder="请输入雷达MAC" />
        </Form.Item>

        <Form.Item label="绑定楼栋" field="buildingId">
          <Select
            allowClear
            placeholder="请选择楼栋"
            options={buildingList?.rows.map((item) => ({
              label: item.name,
              value: item.id,
            }))}
            onChange={async (value) => {
              await api.getBuildingInfoById(value!);
              formRef.setFieldsValue({
                floorId: undefined,
                roomId: undefined,
              });
            }}
          />
        </Form.Item>
        <Form.Item
          // rules={[
          //   {
          //     required: true,
          //     message: '楼层不得为空',
          //   },
          // ]}
          label="绑定楼层"
          field="floorId"
        >
          <Select
            allowClear
            placeholder="请选择楼层"
            disabled={!selectedBuildingId}
            options={buildingInfo?.floors?.map((item) => ({
              label: item.name,
              value: item.id,
            }))}
          />
        </Form.Item>
        <Form.Item
          // rules={[
          //   {
          //     required: true,
          //     message: '房间不得为空',
          //   },
          // ]}
          label="绑定房间"
          field="roomId"
        >
          <Select
            allowClear
            placeholder="请选择房间号"
            disabled={!selectedFloorId}
            options={rooms?.map((item) => ({
              label: item.name,
              value: item.id,
            }))}
          />
        </Form.Item>
        <Form.Item
          label="床位"
          field="bed"
          rules={[
            {
              required: true,
              message: "位置不得为空",
            },
          ]}
        >
          {radarData && (
            <div style={{ display: "none" }}>
              {bed[radarData.bed as keyof typeof bed]}
            </div>
          )}
          <Select
            placeholder="请选择床位"
            disabled={!selectedRoomId}
            defaultValue={bed[radarData?.bed as keyof typeof bed]}
            showSearch
            options={bedList?.map((item) => ({
              label: item.label,
              value: item.value,
            }))}
            onChange={(v) => {
              if (radarData) radarData.bed = v;
            }}
          />
        </Form.Item>
        <Space
          className={css`
            margin-top: 16px;
            padding: 12px 0;
            display: flex;
            justify-content: end;
          `}
        >
          <Button
            type="outline"
            htmlType="button"
            onClick={() => {
              formRef.resetFields();
              onClose?.();
            }}
          >
            取消
          </Button>

          <Button
            type="primary"
            htmlType="submit"
            loading={submitForm.isLoading}
            onClick={() => submitForm.mutateAsync()}
          >
            完成
          </Button>
        </Space>
      </Form>
    </Modal>
  );
};
